package com.keepercloud.qqchat.repository;

import com.keepercloud.qqchat.entity.ChatMessage;
import com.keepercloud.qqchat.entity.UserList;
import org.springframework.data.domain.Example;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @author liyk
 * @date 2019/2/12
 */
@Repository
public interface ChatMessageRepository extends JpaRepository<ChatMessage, Integer> {


    @Override
    <S extends ChatMessage> S save(S entity);

    @Override
    <S extends ChatMessage> long count(Example<S> example);

    Long countByFromUsernameAndToUsername(String fromUsername, String toUsername);

    List<ChatMessage> findByFromUsernameAndToUsernameOrderByHappenedDateDesc(String fromUsername, String toUsername);

    /**
     * 获取来往通信
     * @param fromUsername
     * @param toUsername
     * @param pageStart 获取页数, 用于查询历史记录, 默认只展示最近 20 笔资料
     * @param pageEnd 获取页数, 用于查询历史记录, 默认只展示最近 20 笔资料
     * @return
     */
    @Query(value = "select * from (" +
            "select 0 as type, message , happened_date as date from chat_message where (from_username = ?1 and to_username = ?2) " +
            " union  " +
            "select 1 as type, message , happened_date as date from chat_message where (from_username = ?2 and to_username = ?1) ) t" +
            " order by  date desc limit ?3 , ?4 ", nativeQuery = true)
    List<Map> findByFromUsernameAndToUsername(String fromUsername, String toUsername, Integer pageStart, Integer pageEnd);

}